<?php
/*
This script is used to help automate the Football Pool site.
It is written to run everyday from a windows scheduled task, or
linux cron job at 12:30 everyday.
The script check to see if there is currently a game in progress,
if so it sets of an AJAX script to call a PHP function to get games scores/times
every 30 seconds.
If not, it reloads itself at different intervals based on the day. (More
frequently on days with higher possability of games).

*/
require_once("../include/functions.php");
?>
<html>
  <head>
    <title>JoshHughes.com Football Pool</title>
	<script type="text/javascript" src="scrape.js"></script>
  </head>
<body>
<?php
//check to see if a League value was passed, if not, use NFL by default.
if (($League == NULL) || ($League == ""))
	$League = getLeagueByDate();

//Connect To Database
dbConnect();
$Weeknum = getWeek($League);

//check to make sure $Weeknum > 1 AND $Weeknum < 21
$Weeknum = checkWeekBounds($Weeknum);
echo "<h2>Week $Weeknum</h2>";
if (gameInProgress($Weeknum,$League))
{
	?>
	<script type="text/javascript">
		goScrape('scrape.php?League=<?=$League?>');
	</script>
	<?
	echo "Scraping...<br/>";
}
else//No games in progress, retry later.
{

	//Write SQL Query to extract specified data
	$SQL = "SELECT * FROM ".$League."Schedule Where GameDate=".date("Y-m-d");
	//Open Record Set using SQL Query
	$result = mysql_query($SQL) or die("Cannot query the database.<br>" . mysql_error());
	
	$numGames = mysql_num_rows($result);
	
	if ($numGames > 0)
	{
		echo "There are $numGames games today.<br/>";
	}
	switch (date("w"))	//Decide how much later to retry
	{
		case 0:	//Sunday
			$NumMins = 5;	
			break;
		case 1:	//Monday
			$NumMins = 30;
			break;
		case 4: //Thursday
			$NumMins = 60;
			break;
		case 5: //Friday  (AFL Games are playedon Friday)
			$NumMins = 30;
			break;
		case 6: //Saturday
			$NumMins = 30;
			break;
		default:
			$NumMins = 1440;	//One Day (24 hours)
	}
	
	$TimeOutSecs = $NumMins * 60000;
	$timeAdjust = 5; //Number of hours From GMT + or - to be added
	$timeAdjust += date("I");
	$timeAdjust *= 60;	//60 minutes in an hour
	$timeAdjust *= 60;	//60 seconds in an minute
	
	echo "No $League games in progress <b>".gmdate("l, F jS Y \@ g:i:s A \E\T",time() - $timeAdjust)."</b> ...Trying again in $NumMins minutes.";
	?>
	<script>	
	setTimeout("window.location.reload()", <?= $TimeOutSecs;?>)
	</script>
	<?
}
?>

<div id="State"><br/></div>

</body>
</html>
